package com.clayServer.net.loader
{
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	public class URLLoaderQueue extends EventDispatcher
	{
		public static const ITEM_COMPLETE:String="itemComplete";
		public static const COMPLETE:String="complete";
		
		protected var _isRuning:Boolean=false;
		protected var urlLoader:URLLoader;
		private var request:URLRequest;
		
		protected var _currentItem:LoaderItem;
		private var queue:Vector.<LoaderItem>;
		public function URLLoaderQueue()
		{
			urlLoader=new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE,completeHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,completeHandler);
			
			request=new URLRequest();
			
			queue=new Vector.<LoaderItem>();
		}
		
		public function load():void{
			if(_isRuning)return;
			
			this.loadNext();
			this._isRuning=true;
		}
		
		protected function completeHandler(event:Event):void{
			if(event.type==Event.COMPLETE){
				_currentItem.data=urlLoader.data;
			}
			this.dispatchEvent(new Event(ITEM_COMPLETE));
			
			if(_currentItem.callBack !=null){
				_currentItem.callBack(event);
			}
			loadNext();
		}
		
		
		protected function loadNext():void{
			if(queue.length==0){
				_isRuning=false;
				this.dispatchEvent(new Event(COMPLETE));
				return;
			}
			
			_currentItem=queue.shift();
			
			if(_currentItem.isbinary){
				urlLoader.dataFormat=URLLoaderDataFormat.BINARY;
			}else{
				urlLoader.dataFormat=URLLoaderDataFormat.TEXT;
			}
			
			request.url=_currentItem.path;
			urlLoader.load(request);
		}
		
		/**
		 *  
		 * @param path
		 * @param callBack
		 * @param isbinary
		 * @param key
		 * 
		 */		
		public function add(path:String,callBack:Function=null,isbinary:Boolean=false,key:String=""):void{
			var item:LoaderItem=new LoaderItem();
			item.path=path;
			item.callBack=callBack;
			item.isbinary=isbinary;
			item.key=key;
			queue.push(item);
		}
		
		public function get currentItem():LoaderItem{
			return _currentItem;
		}
	}
}